<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property;

use think\App;
use think\facade\Session;
use think\exception\ValidateException;
use app\validate\property\users\LoginValidate;
use app\common\repositories\users\UsersRepository;
use app\common\repositories\property\users\PropertyUsersRepository;

class Login extends Base
{
    protected $repository;

    public function __construct(App $app, PropertyUsersRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
    }

    /**
     * 用户登录页
     * @return string
     * @throws \Exception
     *
     * @author Amos
     *  2024-01-07 12:35
     */
    public function index()
    {
        return $this->fetch('login/index');
    }

    /**
     * 用户登陆操作
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-01-07 14:35
     */
    public function doLogin()
    {
        if ($this->request->isPost()) {
            validate(LoginValidate::class)->scene('captchalogin')->check($this->request->param());
            try {
                $userInfo = $this->repository->login($this->request->param('username'), $this->request->param('password'));
                $this->repository->setSessionInfo($userInfo);
                return json()->data(['code' => 0, 'msg' => '登陆成功']);
            } catch (ValidateException $e) {
                return json()->data(['code' => -1, 'msg' => $e->getError()]);
            }
        }
    }
}